package com.lynx.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.lynx.controller.model.JobInfo;
import com.lynx.controller.model.Message;
import com.lynx.controller.model.Progress;
import com.lynx.controller.model.Result;
import com.lynx.controller.util.JobInfoUtil;
import com.lynx.core.BaseController;
import com.lynx.service.JobCenterService;
import com.lynx.service.model.JobInfoBO;

/**
 * @author chris.liu
 * @version 5/6/14 4:05 PM
 */
@Controller("jobController")
@SessionAttributes("progress")
@RequestMapping(value = "/job", produces = "text/plain;charset=UTF-8")
public class JobController extends BaseController {

	protected HashMap<String, String> EXT_MAP = new HashMap<String, String>();
	// 最大文件大小 100 M --测试用
	protected long maxSize = 100 * 1024 * 1024;
	// 上传文件的保存路径
	protected String CONFIG_PATH = "/data/tmp/";

	protected String TMP_DIR = "/data/tmp/";

	protected String DIR_NAME = "file";

	public JobController() {
		EXT_MAP.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar");
	}

	@Autowired
	private JobCenterService jobCenterService;

	@RequestMapping(value = "/center", method = RequestMethod.GET)
	public ModelAndView jobCenter(HttpServletRequest request,
			@RequestParam(value = "pageNo", required = false) Integer pageNo) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("job_center");
		if (pageNo == null) {
			pageNo = 1;
		}

		try {
			List<JobInfoBO> bos = jobCenterService.getJobInfos(pageNo);
			List<JobInfo> vos = new LinkedList<JobInfo>();
			for (JobInfoBO bo : bos) {
				vos.add(JobInfoUtil.bo2vo(bo));
			}
			modelAndView.addObject("jobInfos", vos);
		} catch (Exception e) {

		}

		int pageSize = jobCenterService.getJobInfoPageSize();
		modelAndView.addObject("pageSize", pageSize);
		modelAndView.addObject("pageNo", pageNo);
		return modelAndView;
	}

	@ResponseBody
	@RequestMapping(value = "/upload", headers = "Accept=application/json", method = RequestMethod.POST)
	public Result upload(@RequestParam MultipartFile[] files, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		System.out.println("收到用户的文件上传请求");
		Result result = new Result();
		// 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
		// 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		// 设置响应给前台内容的数据格式
		// response.setContentType("text/plain; charset=UTF-8");
		// 设置响应给前台内容的PrintWriter对象
		// PrintWriter out = response.getWriter();
		// 上传文件的原名(即上传前的文件名字)
		String originalFilename = null;
		// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
		// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
		// 上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是files,否则参数里的files无法获取到所有上传的文件
		Message msg;
		for (MultipartFile file : files) {
			if (file.isEmpty()) {
				msg = new Message("错误", "请选择文件后上传");
				result.setStatusCode(Result.RS_FAIL);
				result.setData(msg);
				return null;
			} else {
				originalFilename = file.getOriginalFilename();
				try {
					// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
					// 此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath,
							originalFilename));
				} catch (IOException e) {
					msg = new Message("错误", "文件上传失败，请重试！");
					result.setStatusCode(Result.RS_ERROR);
					result.setData(msg);
					return null;
				}
			}
		}
		result.setStatusCode(Result.RS_OK);
		msg = new Message("成功", "您已成功上传文件！");
		result.setData(msg);
		return result;
	}

	@RequestMapping(value = "/uploadProgress", method = RequestMethod.POST)
	public Result uploadProcess(HttpServletRequest request, Map<String, Object> model) {
		Progress progress = (Progress) request.getSession().getAttribute("progress");
		Result result = new Result();
		if (progress == null) {
			result.setStatusCode(Result.RS_ERROR);
			result.setData(MSG_SYS_ERROR);
		} else {
			result.setStatusCode(Result.RS_OK);
			result.setData(progress);
		}
		return result;
	}

}
